package com.weiwei.diancan.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.TextView;

import com.weiwei.diancan.Contant.Config;
import com.weiwei.diancan.Contant.ConfigMethod;
import com.weiwei.diancan.MyApplicatin;
import com.weiwei.diancan.R;
import com.weiwei.diancan.adapter.OrderDetailAdapter;
import com.weiwei.diancan.base.BaseActivity;
import com.weiwei.diancan.bean.LoginBean;
import com.weiwei.diancan.bean.WaterInfo;
import com.weiwei.diancan.cache.CacheConfig;
import com.weiwei.diancan.http.RetrofitFactory;
import com.weiwei.diancan.utils.ActivityManager;
import com.weiwei.diancan.utils.HttpUtils;
import com.weiwei.diancan.utils.PessmionUtils;
import com.weiwei.diancan.view.BeizhuDialog;
import com.weiwei.diancan.view.EmptyLayout;
import com.weiwei.diancan.view.SimpleSwipeRefreshLayout;
import com.weiwei.diancan.view.TbandDialog;
import com.weiwei.diancan.view.UpdateDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;

import java.text.DecimalFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;
import weiwei.com.weiweilibrary.views.ToastUtil;

public class OrderDetailActivity extends BaseActivity {

    private TbandDialog tbandDialog;
    private RecyclerView recycler;
    private UpdateDialog updateDialog;
    private OrderDetailAdapter adapter;
    private TextView tv_biangeng;
    private TextView tv_load_update;
    private BeizhuDialog beizhuDialog;
    private LoginBean.TypeListBean.TabListBean tabListBean;
    private EmptyLayout emptyLayout;
    private SimpleSwipeRefreshLayout refresh;
    private String type;
    private TextView tv_caipin;
    private TextView tv_shuliang;
    private TextView tv_jiage;
    private String tabId;
    private String waiter_jurisdiction;

    @Override
    public void getData() {

    }

    @Override
    public void setListeners() {

        tv_load_update.setOnClickListener(v ->{

            String orderId = null;
            List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
            for(LoginBean.OrderListBean orderListBean:order_list){
                if(orderListBean.getOrder_type().equals("0")){
                    orderId = orderListBean.getOrder_id();
                }
            }
            Bundle bundle = new Bundle();
            bundle.putString("order_id", orderId);
            bundle.putInt("type", 3);
            openActivity(PayActivity.class, bundle);
        });

        /**
         * 备注
         */
        beizhuDialog.setListener((v, text) -> {
            String s = beizhuDialog.getEt_num().getText().toString();
            if(TextUtils.isEmpty(s)){
                ToastUtil.showToast(OrderDetailActivity.this,"请输入备注信息");
                return;
            }
            beizhuDialog.cancel();
            String orderId = null;
            List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
            for(LoginBean.OrderListBean orderListBean:order_list){
                String order_type = orderListBean.getOrder_type();
                if(order_type.equals("0")){
                    orderId = orderListBean.getOrder_id();
                }
            }
            beizhu(orderId,text);
        });
        /**
         * 操作变更
         */
        tv_biangeng.setOnClickListener(v->tbandDialog.show());

        /**
         * 人数变更
         */
        updateDialog.setListener((v,text,tabListBean) -> {
            if (TextUtils.isEmpty(text)){
                ToastUtil.showToast(OrderDetailActivity.this,"请输入人数");
                return;
            }else{
                updateDialog.cancel();
                String orderId = null;
                List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
                for(LoginBean.OrderListBean orderListBean:order_list){
                    String order_type = orderListBean.getOrder_type();
                    if(order_type.equals("0")){
                        orderId = orderListBean.getOrder_id();
                    }
                }
                upPeople(orderId,text);
            }

        });
        /**
         * 弹出框
         */
        tbandDialog.setPayListener((which)->{
            if(!PessmionUtils.check(OrderDetailActivity.this,"1")){
                tbandDialog.cancel();
                return;
            }
                switch (which){
                    case 0:

                        Bundle bundle = new Bundle();
                        bundle.putSerializable("tabListBean", tabListBean);
                        bundle.putString("num","-1");
                        openActivity(OpenActivity.class, bundle);
                        break;
                    case 1:
                        updateDialog.setTabListBean(tabListBean);
                        updateDialog.show();
                        break;
                    case 2:
                        MyApplicatin.tab_id = tabListBean.getTab_id();

                        List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
                        for(LoginBean.OrderListBean orderListBean:order_list){
                            String order_type = orderListBean.getOrder_type();
                            if(order_type.equals("0")){
                                MyApplicatin.order_id = orderListBean.getOrder_id();
                            }
                        }
                        ToastUtil.showToast(OrderDetailActivity.this,"请选择空闲餐桌");
                        EventBus.getDefault().post(Config.KAIZHUO);
                        openActivity(Main1Activity.class,null);
                        break;
                    case 3:
                        beizhuDialog.show();
                        break;
            }
            tbandDialog.cancel();
        });

        /**
         * 订单列表点击
         */
        adapter.setListener(new OrderDetailAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View v, int pos) {
                Bundle bundle = new Bundle();
                LoginBean.OrderListBean orderListBean = tabListBean.getOrder_list().get(pos);
                bundle.putSerializable("data",orderListBean);
                openActivity(OrderDetailAndActivity.class, bundle);
            }

            @Override
            public void onShanchu(String orderId, String logId, OrderDetailAdapter.MenuAdapter menuAdapter) {
                if(!PessmionUtils.check(OrderDetailActivity.this,"2")){
                    return;
                }
                detelOrder(orderId,logId,menuAdapter);
            }


            @Override
            public void onJiezhang(String orderId, LoginBean.OrderListBean item,TextView textView) {
                if(!PessmionUtils.check(OrderDetailActivity.this,"3")){
                    return;
                }
                if(textView.getText().toString().equals("结账")) {
                    String best_orderId = null;
                    List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
                    for(LoginBean.OrderListBean orderListBean:order_list){
                        if(orderListBean.getOrder_type().equals("0")){
                            best_orderId = orderListBean.getOrder_id();
                        }
                    }
                    Bundle bundle = new Bundle();
                    bundle.putString("best_orderId", best_orderId);
                    bundle.putString("order_id", orderId);
                    bundle.putInt("type", 1);
                    openActivity(PayActivity.class, bundle);
                }
            }
        });

        refresh.setOnRefreshListener(() -> {
            onRefreshData();
        });
    }

    @Override
    public void initView() {
        recycler = (RecyclerView)findViewById(R.id.recycler);
        refresh = (SimpleSwipeRefreshLayout)findViewById(R.id.refresh);
        refresh.setColorSchemeColors(Color.parseColor("#B41B1B"));
        recycler.setOnScrollListener(new RecyclerView.OnScrollListener(){
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                int topRowVerticalPosition =
                        (recyclerView == null || recyclerView.getChildCount() == 0) ? 0 : recyclerView.getChildAt(0).getTop();
                refresh.setEnabled(topRowVerticalPosition >= 0);

            }

            @Override
            public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
                super.onScrollStateChanged(recyclerView, newState);
            }
        });

        recycler.setLayoutManager(new LinearLayoutManager(this));
        tv_caipin = (TextView)findViewById(R.id.tv_caipin);
        tv_shuliang = (TextView)findViewById(R.id.tv_shuliang);
        tv_jiage = (TextView)findViewById(R.id.tv_jiage);



        updateDialog = new UpdateDialog(this);
        beizhuDialog = new BeizhuDialog(this);
        beizhuDialog.getEt_num().setHint(tabListBean.getTab_name());

        tv_biangeng = (TextView)findViewById(R.id.tv_biangeng);
        tv_load_update = (TextView)findViewById(R.id.tv_load_update);

        emptyLayout = (EmptyLayout)findViewById(R.id.emptyLayout);
        if(tabListBean.getOrder_list() == null ||tabListBean.getOrder_list().size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }else{
            adapter = new OrderDetailAdapter(tabListBean.getOrder_list(),this);
            recycler.setAdapter(adapter);
        }

        initPrice();
    }

    private void initPrice() {
        DecimalFormat df = new DecimalFormat("#.00");
        if(tabListBean.getOrder_list() == null ||tabListBean.getOrder_list().size() == 0){
            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
        }
        double num = 0;
        double price = 0;
        int shuliang = 0;
        List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
        if(order_list!=null){
            for(int i = 0;i<order_list.size();i++){
                LoginBean.OrderListBean orderListBean = order_list.get(i);
                if(orderListBean.getLog_list()!=null){
                    List<LoginBean.OrderListBean.LogListBean> log_list = order_list.get(i).getLog_list();
                    for(int j = 0;j<log_list.size();j++){
                        String log_count = log_list.get(j).getLog_count();
                        String log_price = log_list.get(j).getLog_price();

                        double i1 = Double.parseDouble(log_count);
                        double v = Double.parseDouble(log_price);
                        num+=i1;
                        price+=v*i1;
                    }
                    shuliang+=log_list.size();
                }
            }
        }

        tv_caipin.setText(shuliang+"");
        tv_shuliang.setText(num+"");
        if(price == 0){
            tv_jiage.setText("¥0.00");
        }else {
            tv_jiage.setText("¥"+df.format(price));
        }
    }

    @Override
    public void initTitle() {
        titler.setText("订单详情("+tabListBean.getTab_name()+")");

        iv_left.setVisibility(View.VISIBLE);
        iv_left.setText("返回");
        iv_left.setOnClickListener((v)->finish());

        iv_right.setText("全部结账");
        iv_right.setVisibility(View.VISIBLE);
        tbandDialog = new TbandDialog(this);
        iv_right.setOnClickListener(v->{
            if(!PessmionUtils.check(OrderDetailActivity.this,"3")){
                return;
            }
            String orderId = null;
            List<LoginBean.OrderListBean> order_list = tabListBean.getOrder_list();
            for(LoginBean.OrderListBean orderListBean:order_list){
                if(orderListBean.getOrder_type().equals("0")){
                    orderId = orderListBean.getOrder_id();
                }
            }

            Bundle bundle = new Bundle();
            bundle.putString("order_id",orderId);
            bundle.putInt("type",0);
            openActivity(PayActivity.class,bundle);
        });
    }
    @Override
    public void setLayoutView() {
       setContentView(R.layout.activity_order_detail);
        EventBus.getDefault().register(this);


        ActivityManager.getInstance().pushOneActivity(this);
        tabId = getIntent().getExtras().getString("tabListBean");
        type = getIntent().getExtras().getString("type");
        LoginBean login = CacheConfig.getInst().getLogin();
        List<LoginBean.TypeListBean> type_list = login.getType_list();

        for(LoginBean.TypeListBean typeListBean:type_list){
            List<LoginBean.TypeListBean.TabListBean> tab_list = typeListBean.getTab_list();
            for(LoginBean.TypeListBean.TabListBean tabs:tab_list){
                if(tabId.equals(tabs.getTab_id())){
                    tabListBean = tabs;
                }
            }
        }

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ActivityManager.getInstance().popOneActivity(this);
        EventBus.getDefault().unregister(this);
    }

    @Subscribe
    public void onEvent(String s) {
        if (s.equals(Config.LOGIN_SUCCESS)) {
            onRefreshData();
        }else if(s.equals("finish")){
            finish();
        }else if(s.equals("refrsh")){
            onRefreshData();
        }
    }

    /**
     * 删除商品
     */
    private void detelOrder(String orderId, String logId, OrderDetailAdapter.MenuAdapter menuAdapter){
        progressDialog.setMessage("删除中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.log_id,logId);
        RetrofitFactory.getIntance().deleteOrder(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        HttpUtils.check(loginBean, OrderDetailActivity.this, loginBean1 -> {
                            List<LoginBean.TypeListBean> type_list = loginBean1.getType_list();

                            for(LoginBean.TypeListBean typeListBean:type_list){
                                List<LoginBean.TypeListBean.TabListBean> tab_list = typeListBean.getTab_list();
                                for(LoginBean.TypeListBean.TabListBean tabs:tab_list){
                                    if(tabId.equals(tabs.getTab_id())){
                                        tabListBean = tabs;
                                    }
                                }
                            }
                            adapter.setNewData(tabListBean.getOrder_list());
                            menuAdapter.notifyDataSetChanged();
                            initPrice();
                            Log.e("tag",tabListBean.getOrder_list().toString());
                        });
//                        if (loginBean.getIs_success().equals("1")) {
//                            loginBean.setShop_token(CacheConfig.getInst().getToken(OrderDetailActivity.this));
//                            CacheConfig.getInst().putData(loginBean);
//                            EventBus.getDefault().post(loginBean);
//
//                            for (LoginBean.TypeListBean typeListBean : loginBean.getType_list()) {
//                                if (typeListBean.getType_id().equals(type)) {
//                                    for (LoginBean.TypeListBean.TabListBean tabListBean1 : typeListBean.getTab_list()) {
//                                        if (tabListBean1.getTab_id().equals(tabListBean.getTab_id())) {
//                                            tabListBean = tabListBean1;
//                                        }
//                                    }
//                                }
//                            }
//
//                            if (tabListBean.getOrder_list() == null || tabListBean.getOrder_list().size() == 0) {
//                                emptyLayout.setErrorType(EmptyLayout.NO_DATA, EmptyLayout.NOT_DATA);
//                            } else {
//                                emptyLayout.setVisibility(View.GONE);
//                                Log.e("tag",tabListBean.getOrder_list().toString());
//                                adapter.setNewData(tabListBean.getOrder_list());
//                                menuAdapter.notifyDataSetChanged();
//                            }
//                        }else{
//                            ToastUtil.showToast(OrderDetailActivity.this,loginBean.getReason());
//                            if(loginBean.getIs_success().equals("-1")){
//                                openActivity(LoginActivity.class,null);
//                                OrderDetailActivity.this.finish();
//                            }else if(loginBean.getIs_success().equals("-2")){
//                                openActivity(BangdingActivity.class,null);
//                                OrderDetailActivity.this.finish();
//                            }
//                        }
                        progressDialog.cancel();
                    }
                });
    }


    /**
     * 刷新订单
     */
    private void onRefreshData(){
        if(TextUtils.isEmpty(CacheConfig.getInst().getToken(this))){
            ToastUtil.showToast(this,"没有登录！");
            refresh.setRefreshing(false);
            return;
        }

        if(TextUtils.isEmpty(CacheConfig.getInst().getWaterToken(this))){
            ToastUtil.showToast(this,"请绑定工号！");
            refresh.setRefreshing(false);
            return;
        }

        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        RetrofitFactory.getIntance().refreshData(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {
                        refresh.setRefreshing(false);
                    }

                    @Override
                    public void onError(Throwable e) {
                        refresh.setRefreshing(false);
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        loginBean.setShop_token(CacheConfig.getInst().getToken(OrderDetailActivity.this));
                        CacheConfig.getInst().putData(loginBean);

                        for(LoginBean.TypeListBean typeListBean:loginBean.getType_list()){
                            if(typeListBean.getType_id().equals(type)){
                                for(LoginBean.TypeListBean.TabListBean tabListBean1:typeListBean.getTab_list()){
                                    if(tabListBean1.getTab_id().equals(tabListBean.getTab_id())){
                                        tabListBean = tabListBean1;
                                    }
                                }
                            }
                        }

                        if(tabListBean.getOrder_list() == null ||tabListBean.getOrder_list().size() == 0){
                            emptyLayout.setErrorType(EmptyLayout.NO_DATA,EmptyLayout.NOT_DATA);
                        }else{
                            emptyLayout.setVisibility(View.GONE);
                            adapter.setNewData(tabListBean.getOrder_list());
                        }
                        initPrice();
                    }
                });
    }

    /**
     * 修改就餐人数
     */
    private void upPeople(String orderId,String order_person){
        progressDialog.setMessage("人数修改中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.order_person,order_person);
        RetrofitFactory.getIntance().person_upd(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, OrderDetailActivity.this, loginBean1 -> {
                            ToastUtil.showToast(OrderDetailActivity.this,loginBean1.getReason());
                        });
                    }
                });
    }

    /**
     * 备注
     */
    private void beizhu(String orderId,String log_desc){
        progressDialog.setMessage("备注上传中...");
        progressDialog.show();
        Map<String,String> map = new HashMap<>();
        map.put(ConfigMethod.shop_token,CacheConfig.getInst().getToken(this));
        map.put(ConfigMethod.waiter_token,CacheConfig.getInst().getWaterToken(this));
        map.put(ConfigMethod.order_id,orderId);
        map.put(ConfigMethod.log_desc, log_desc);
        RetrofitFactory.getIntance().add_order_log(map)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<LoginBean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        progressDialog.cancel();
                        emptyLayout.setErrorType(EmptyLayout.NETWORK_ERROR,-1);
                    }

                    @Override
                    public void onNext(LoginBean loginBean) {
                        progressDialog.cancel();
                        HttpUtils.check(loginBean, OrderDetailActivity.this, loginBean1 -> {
                            ToastUtil.showToast(OrderDetailActivity.this,loginBean1.getReason());
                        });
                    }
                });
    }
}
